package com.fjwt.gz.sync.zhenghaoyou;

import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjwt.gz.core.ctrls.AbstractCtrl;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.db.entity.FansEntity;
import com.fjwt.gz.db.vo.FansCouponsDetailVo;
import com.fjwt.gz.db.vo.FansCouponsVo;
import com.fjwt.gz.service.impl.ActivityService;
import com.fjwt.gz.service.impl.AwardCouponService;
import com.fjwt.gz.service.impl.FansService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

@RestController
@Slf4j
@RequestMapping("/api/fansDataConnect")
public class FansDataConnectController extends AbstractCtrl {

    @Autowired
    private FansService fansService;

    @Autowired
    private ActivityService activityService;
    @Autowired
    private AwardCouponService awardCouponService;

    @Value("${fans.key}")
    private String KEY;

    /**
     * 同步商户身份信息
     */
    @PostMapping("/syncFansMchInfo")
    public ApiRes syncFansMchInfo() {
        String openIdStr = getValString("payOpenId");
        String agentNo = getValString("agentNo");//郑好邮系统固定传郑州的agentNo
        if (StringUtils.isEmpty(openIdStr) || StringUtils.isEmpty(agentNo)) {
            return ApiRes.customFail("网络故障,请稍后重试");
        }
        SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", KEY.getBytes(StandardCharsets.UTF_8));
        String openId = sm4.decryptStr(openIdStr);
        agentNo = sm4.decryptStr(agentNo);
        FansEntity fansEntity = fansService.selectFansByOpenId(openId, agentNo);
        if (ObjectUtils.isEmpty(fansEntity)) {
            return ApiRes.customFail("该用户不存在");
        }
        JSONObject object = fansService.syncFansMchInfo(fansEntity, agentNo);
        return ApiRes.ok(sm4.encryptHex(object.toJSONString()));
    }

    /**
     * 卡券数量统计
     *
     * @return
     */
    @PostMapping("/syncFansCouponNum")
    public ApiRes syncFansCouponNum() {
        String openIdStr = getValString("payOpenId");
        String agentNo = getValString("agentNo");
        if (StringUtils.isEmpty(openIdStr)) {
            return ApiRes.customFail("网络故障,请稍后重试");
        }
        SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", KEY.getBytes(StandardCharsets.UTF_8));
        String openId = sm4.decryptStr(openIdStr);
        FansEntity fansEntity = fansService.selectFansByOpenId(openId,sm4.decryptStr(agentNo));
        if (ObjectUtils.isEmpty(fansEntity)) {
            return ApiRes.customFail("该用户不存在");
        }
        return ApiRes.ok(sm4.encryptHex(fansService.syncFansCouponNum(fansEntity)));
    }

    /**
     * 同步会员卡券列表
     */
    @PostMapping("/syncFansCouponList")
    public ApiRes syncFansCouponList() {
        String couponListStr = getValString("couponList");
        String agentNo = getValString("agentNo");
        if (StringUtils.isEmpty(couponListStr)) {
            return ApiRes.customFail("网络故障,请稍后重试");
        }
        SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", KEY.getBytes(StandardCharsets.UTF_8));
        String all = couponListStr.replaceAll("\"", "");
        String couponList = sm4.decryptStr(all);
        JSONObject object = JSONObject.parseObject(couponList);
        log.info("请求参数解密：{}", object.toJSONString());
        String openId = object.getString("payOpenId");
        if (StringUtils.isEmpty(openId)) {
            return ApiRes.customFail("网络故障,请稍后重试");
        }
        FansEntity fansEntity = fansService.selectFansByOpenId(openId,sm4.decryptStr(agentNo));
        if (ObjectUtils.isEmpty(fansEntity)) {
            return ApiRes.customFail("该用户不存在");
        }
        IPage<FansCouponsVo> list = fansService.syncFansCouponList(new Page(object.getIntValue("num"), object.getIntValue("size")), fansEntity.getFansId(), object);
        return ApiRes.ok(sm4.encryptHex(JSONObject.toJSONString(list)));
    }

    /**
     * 同步活动列表
     */
    @PostMapping("/syncActiveList")
    public ApiRes syncActiveList() {
        String activeList = getValString("activeList");
        if (StringUtils.isEmpty(activeList)) {
            return ApiRes.customFail("网络故障,请稍后重试");
        }
        SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", KEY.getBytes(StandardCharsets.UTF_8));
        String all = activeList.replaceAll("\"", "");
        String couponList = sm4.decryptStr(all);
        JSONObject object = JSONObject.parseObject(couponList);
        log.info("请求参数解密：{}", object.toJSONString());
        Page page = new Page(object.getIntValue("num"), object.getIntValue("size"));
        IPage<ActivityEntity> list = activityService.selectActivityListByAppid(page, object.getString("appid"));
        log.info("从郑邮享同步活动列表返回数据是：{}",JSONUtil.toJsonStr(list));
        return ApiRes.ok(sm4.encryptHex(JSONObject.toJSONString(list)));
    }

    /**
     * 活动详情接口
     */
    @PostMapping("/syncActiveDetail")
    public ApiRes syncActiveDetail() {
        String activityId = getValString("activityId");
        String agentNo = getValString("agentNo");
        String entryway = getValString("entryway");
        if (StringUtils.isEmpty(activityId) || StringUtils.isEmpty(agentNo) || StringUtils.isEmpty(entryway)) {
            return ApiRes.customFail("请求参数缺失");
        }
        SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", KEY.getBytes(StandardCharsets.UTF_8));
        String all = activityId.replaceAll("\"", "");
        String activityIdDb = sm4.decryptStr(all);
        String agentNoDb = sm4.decryptStr(agentNo);
        String entrywayDb = sm4.decryptStr(entryway);
        log.info("请求参数解密：{}", activityId);

        ActivityEntity activityEntity = activityService.getActivityToOutById(Long.valueOf(activityIdDb),Long.valueOf(entrywayDb),agentNoDb);
        return ApiRes.ok(sm4.encryptHex(JSONObject.toJSONString(activityEntity)));
    }


    /**
     * 卡券详情接口
     */
    @RequestMapping(value = "/awardDetails", method = RequestMethod.POST)
    public ApiRes details() {
        Long couponId = getValLong("couponId");
        Long fansAwardId = getValLong("fansAwardId");
        Long goodsId = getValLong("goodsId");
        Long virtualAwardId = getValLong("virtualAwardId");

        if (couponId == null && fansAwardId == null && goodsId == null && virtualAwardId == null) {
            return ApiRes.customFail("网络故障,请稍后重试");
        }
        SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", KEY.getBytes(StandardCharsets.UTF_8));

        String couponIdDe = sm4.decryptStr(couponId.toString());
        String fansAwardIdDe = sm4.decryptStr(fansAwardId.toString());
        String goodsIdDe = sm4.decryptStr(goodsId.toString());
        String virtualAwardIdDe = sm4.decryptStr(virtualAwardId.toString());

        log.info("C端用户奖品详情接口调用，请求地址：/api/award/coupon/details，请求参数：用户奖品id：{}，卡券id：{}，实物id：{}",fansAwardId,couponId,goodsId);
        FansCouponsDetailVo vo = awardCouponService.getFansCouponDetail(Long.valueOf(couponIdDe),Long.valueOf(goodsIdDe),Long.valueOf(fansAwardIdDe), Long.valueOf(virtualAwardIdDe));
        log.info("C端用户奖品详情接口调用，请求地址：/api/award/coupon/details，返回结果：{}", JSONUtil.toJsonStr(vo));
        return ApiRes.ok(vo);
    }

}
